package com.coder.rental.security;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author XueWenJie
 * @Date 2025/2/1
 * @Project auto_rental
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private LoginFailHandler loginFailHandler;
    @Resource
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;
    @Resource
    private CustomerAnonymousEntryPoint customerAnonymousEntryPoint;
    @Resource
    private CustomerUserDetailsService customerUserDetailsService;

    @Resource
    private VerifyTokenFilter verifyTokenFilter;

    /**
     * 配置安全过滤链
     *
     * @param http 用于配置HttpSecurity的接口
     * @return 返回构建好的SecurityFilterChain对象
     * @throws Exception 如果配置过程中发生错误，则抛出异常
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 登录前过滤配置
        http.addFilterBefore(verifyTokenFilter, UsernamePasswordAuthenticationFilter.class);

        http.formLogin()
                // 设置登录处理URL
                .loginProcessingUrl("/rental/user/login")
                // 设置登录成功处理器
                .successHandler(loginSuccessHandler)
                // 设置登录失败处理器
                .failureHandler(loginFailHandler)
                .and()
                .sessionManagement()
                //设置会话创建策略为无状态
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 授权请求配置
                .authorizeHttpRequests()
                //匹配登录请求
                .requestMatchers("/rental/user/login")
                // 允许所有请求访问
                .permitAll()
                //任何其他请求需要认证
                .anyRequest().authenticated()
                .and()
                // 异常处理配置
                .exceptionHandling()
                //设置未认证入口点
                .authenticationEntryPoint(customerAnonymousEntryPoint)
                //设置访问 拒绝处理器
                .accessDeniedHandler(customerAccessDeniedHandler)
                .and()
                // 跨域配置
                .cors()
                .and()
                // 关闭CSRF保护 跨站请求伪造 是一种网络攻击
                .csrf().disable()
                //设置用户详情服务
                .userDetailsService(customerUserDetailsService);
        // 构建并返回安全过滤链
        return http.build();
    }
}
